package com.itheima.d0_feedback.feedback3.src.d11_proxy.demo;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Test {
    public static void main(String[] args) {
        //业务类和动态代理生成的类都实现了相同的接口。

        UserService userService = new UserServiceImpl();

        UserService proxy = getProxy(userService);
        boolean b = proxy.deleteUsers();

    }

    public static <T> T getProxy(T obj) {

        return (T) Proxy.newProxyInstance(
                obj.getClass().getClassLoader(),
                obj.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        long t1 = System.currentTimeMillis();
                        //业务方法执行
                        Object result = method.invoke(obj, args);

                        long t2 = System.currentTimeMillis();
                        System.out.println(method.getName() + "花费时间" + (t2 - t1) + "毫秒");

                        return result;
                    }
                }
        );
    }


}
